const fs = require('fs');
const path = require('path');
const axios = require('axios');
const COS = require('cos-nodejs-sdk-v5');
const stage = process.env.STAGE.trim()
const isDev = stage === 'dev';
const publish_token =
    `eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjQ3ODM3MzcyNzUsImlhdCI6MTYyODA2MzY3NSwibW9iaWxlIjoiLSIsImVtYWlsIjoiLSIsImdfaWQiOiJtYWxsLW1vYmlsZSIsInVzZXJfbmFtZSI6IuadpeiHqm1hbGwtbW9iaWxl55qEYXBp6LCD55SoIn0.bSsDpaZ2zQV0YVyWox74uPYCWc595p_zef0s8ZYf0BoXyLXBnNAk_YXWndu7yQDp7CPyrPaOSkKQ8f8PoIHvBiLd2eu29KXgv4hZzgnHZwtICIJsON9Cm5ugq0HDvmxE3cJUzhdeNZnS-_eg4Z8zNCqqITir0Bng48lWS8Y1cKE`
console.log(`isDev=>${isDev}`)
const distRoot = `./dist`
// const distRoot = `./dist/${stage}`
const resource_bucket_prefix = isDev ? `resource-dev`: `resource`
const resource_bucket_name = `${resource_bucket_prefix}-1306337005`
const resource_bucket_domain = isDev ? `https://resource-dev.bucket.biling.club`: `https://resource.bucket.biling.club`
console.log(`resource_bucket_name=>${resource_bucket_name}`)
console.log(`resource_bucket_domain=>${resource_bucket_domain}`)
const spliter =
    `------------------------------------------------------------------------------------`

const domain = isDev ? `https://bilinadmin.dev.biling.club` : `https://bilinadmin.api.biling.club`
const authUrl = `${domain}/admin/api/vendor/v1/cos/authorization`
console.log(`authUrl=>${authUrl}`)
const cos = new COS({
    // 必选参数
    getAuthorization: function (options, callback) {

        axios({
                method: 'POST',
                url: authUrl,
                headers: {
                    'G-Token': publish_token
                },
                data: {
                    bucket_prefix: resource_bucket_prefix,
                },
            }).then(resp => {
                const data = resp.data.data
                if (!data || !data.credentials) {
                    console.error("bucket credentials invalid")
                    return
                }
                var credentials = {
                    TmpSecretId: data.credentials.tmp_secret_id,
                    TmpSecretKey: data.credentials.tmp_secret_key,
                    SecurityToken: data.credentials.session_token,
                    // 建议返回服务器时间作为签名的开始时间，避免用户浏览器本地时间偏差过大导致签名错误
                    // StartTime: data.startTime, // 时间戳，单位秒，如：1580000000
                    ExpiredTime: data.credentials
                        .expired_time, // 时间戳，单位秒，如：1580000900
                }

                callback(credentials);
            })
            .catch(function (error) {
                console.error('Error ' + error.message)
            })
    }
})



const uploadFile = function (key, file) {
    cos.putObject({
        Bucket: resource_bucket_name,
        /* 必须 */
        Region: 'ap-shanghai',
        /* 必须 */
        Key: key,
        /* 必须 */
        StorageClass: 'STANDARD',
        Body: fs.createReadStream(file), // 上传文件对象
        onProgress: function (progressData) {
            console.log(JSON.stringify(progressData));
        }
    }, function (err, data) {
        console.log(err || data);
    });
};

console.log(spliter)

// 处理根目录的
const soleDir = `${distRoot}/sole/`
const soleDirPath = path.join(__dirname, soleDir)
const soleDirKeys = []
console.log(`处理sole目录下=>${soleDirPath}`)
const soleDirJsFiles = fs.readdirSync(soleDirPath).filter(item => /.*\.js$/.test(item));
for (let fileKey of soleDirJsFiles) {
    let localFile = `${soleDirPath}${fileKey}`
    console.log(`fileKey=>${fileKey}`)
    console.log(`localFile=>${localFile}`)
    uploadFile(fileKey, localFile);
    soleDirKeys.push(fileKey)
}
console.log(`soleDirKeys=>${soleDirKeys}`)

console.log(spliter)
// const filename_0 = soleDirJsFiles.filter(item => /0\..*\.js/.test(item))[0];
// const filename_1 = soleDirJsFiles.filter(item => /1\..*\.js/.test(item))[0];
// console.log(`filename_0=>${filename_0}`)
// console.log(`filename_1=>${filename_1}`)
// const localFile_0 = path.join(__dirname, `${distRoot}/sole/${filename_0}`);
// const localFile_1 = path.join(__dirname, `${distRoot}/sole/${filename_1}`);
// console.log(`localFile_0=>${localFile_0}`)
// console.log(`localFile_1=>${localFile_1}`)
// const key_0 = filename_0;
// const key_1 = filename_1;
// console.log(`key_0=>${key_0}`)
// console.log(`key_1=>${key_1}`)

// uploadFile(key_0, localFile_0);
// uploadFile(key_1, localFile_1);

const soleSlashJsDir = `${soleDir}js/`
const soleSlashJsDirPath = path.join(__dirname, soleSlashJsDir)
const soleSlashJsDirKeys = []
console.log(`处理sole/js目录下=>${soleSlashJsDirPath}`)
const soleSlashJsDirJsFiles = fs.readdirSync(soleSlashJsDirPath).filter(item => /.*\.js$/.test(
    item));
for (let fileKey of soleSlashJsDirJsFiles) {
    let localFile = `${soleSlashJsDirPath}${fileKey}`
    console.log(`fileKey=>${fileKey}`)
    console.log(`localFile=>${localFile}`)
    uploadFile(fileKey, localFile);
    soleSlashJsDirKeys.push(fileKey)
}
console.log(`soleSlashJsDirKeys=>${soleSlashJsDirKeys}`)
console.log(spliter)
// const js_filename_redirect = soleSlashJsDirJsFiles.filter(item => /redirect\..*\.js/.test(item))[0];
// const js_filename_shop = soleSlashJsDirJsFiles.filter(item => /shop\..*\.js/.test(item))[0];
// console.log(`js_filename_redirect=>${js_filename_redirect}`)
// console.log(`js_filename_shop=>${js_filename_shop}`)
// const localFile_redirect = path.join(__dirname, `${distRoot}/sole/js/${js_filename_redirect}`);
// const localFile_shop = path.join(__dirname, `${distRoot}/sole/js/${js_filename_shop}`);
// console.log(`localFile_redirect=>${localFile_redirect}`)
// console.log(`localFile_shop=>${localFile_shop}`)

// // 上传css文件
// uploadFile(js_filename_redirect, localFile_redirect);
// uploadFile(js_filename_shop, localFile_shop);



// 处理css样式文件
const soleSlashCssDir = `${soleDir}css/`
const soleSlashCssDirPath = path.join(__dirname, soleSlashCssDir)
const soleSlashCssDirKeys = []
console.log(`处理sole/css目录下=>${soleSlashCssDirPath}`)
const soleSlashCssFiles = fs.readdirSync(soleSlashCssDirPath).filter(item => /.*\.css$/.test(item));
for (let fileKey of soleSlashCssFiles) {
    let localFile = `${soleSlashCssDirPath}${fileKey}`
    console.log(`fileKey=>${fileKey}`)
    console.log(`localFile=>${localFile}`)
    uploadFile(fileKey, localFile);
    soleSlashCssDirKeys.push(fileKey)
}
console.log(`soleSlashCssDirKeys=>${soleSlashCssDirKeys}`)
console.log(spliter)

const changeValue = function (name, commonJSArr, jsFileNames, cssFileNames) {
    const htmlFilePath = path.join(__dirname, `${distRoot}/${name}`);
    let fileContent = fs.readFileSync(htmlFilePath, 'utf8');
    for (let i = 0; i < commonJSArr.length; i++) {
        fileContent = fileContent.replace(`/sole/${commonJSArr[i]}`,
            `${resource_bucket_domain}/${commonJSArr[i]}`);
    }
    for (let i = 0; i < jsFileNames.length; i++) {
        fileContent = fileContent.replace(`/sole/js/${jsFileNames[i]}`,
            `${resource_bucket_domain}/${jsFileNames[i]}`);
    }
    for (let i = 0; i < cssFileNames.length; i++) {
        fileContent = fileContent.replace(`/sole/css/${cssFileNames[i]}`,
            `${resource_bucket_domain}/${cssFileNames[i]}`);
    }
    fs.writeFileSync(path.join(__dirname, `${distRoot}/${name}`), fileContent, 'utf8');
};

fs.readdir(path.join(__dirname, `${distRoot}/`), 'utf8', function (err, data) {
    if (err) console.log(err);
    for (let i = 0; i < data.length; i++) {
        const item = data[i];
        if (/\.html/g.test(item)) {
            console.log(`html=>${item}`)
            changeValue(item, soleDirKeys, soleSlashJsDirKeys, soleSlashCssDirKeys);
        }
    }
});
